
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;


using JYJ.AiYard.StationManagement.TbObjects;
using JYJ.AiYard.StationManagement.TbObjects.Dtos;
using JYJ.AiYard.StationManagement.TbObjects.DomainService;
using JYJ.AiYard.StationManagement.TbObjects.Authorization;
using JYJ.AiYard.Database;

namespace JYJ.AiYard.StationManagement.TbObjects
{
    /// <summary>
    /// TbObjects应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class TbObjectsAppService : AiYardAppServiceBase, ITbObjectsAppService
    {
        private readonly IRepository<TbObjects, long> _entityRepository;

        private readonly ITbObjectsManager _entityManager;

        private readonly IAiYardDbTableIssuedCard _aiYardDbTableIssuedCard;

        /// <summary>
        /// 构造函数 
        ///</summary>
        public TbObjectsAppService(
        IRepository<TbObjects, long> entityRepository
        ,ITbObjectsManager entityManager,
        IAiYardDbTableIssuedCard aiYardDbTableIssuedCard
        )
        {
            _entityRepository = entityRepository; 
             _entityManager=entityManager;
            _aiYardDbTableIssuedCard = aiYardDbTableIssuedCard;
        }


        /// <summary>
        /// 获取TbObjects的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[AbpAuthorize(TbObjectsPermissions.Query)] 
        public async Task<PagedResultDto<TbObjectsListDto>> GetPaged(GetTbObjectssInput input)
		{
            //查询 
            // TODO:根据传入的参数添加过滤条件 
            var query1 = _aiYardDbTableIssuedCard.GetTbObjects(GetCurrenUserOrganizationAndChildrenUnit(), input.FilterText);

            var query = query1.AsQueryable();
            var count = query.Count();

            //var count = await query.CountAsync();

			var entityList = query               
                    .OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToList();
             
			var entityListDtos =entityList.MapTo<List<TbObjectsListDto>>();

			return new PagedResultDto<TbObjectsListDto>(count,entityListDtos);
		}


        /// <summary>
        /// 获取所有的类别
        /// </summary>
        /// <returns></returns>
        public async Task<List<TbObjectsListDto>> GetAllTbObject(int Obj_Type, long StationId)
        {
            var tbDepart = await _entityRepository.GetAll().Where(o => o.Station_ID == StationId && o.OBJ_TYPE == Obj_Type && o.OBJ_ID!= 1406 && o.OBJ_ID != 1407 && o.OBJ_ID != 1408).ToListAsync();

            var allTbDepart = tbDepart.MapTo<List<TbObjectsListDto>>();    

            return allTbDepart;
        }

        public async Task<List<StationObjectsDTO>> GetAllTbObjectIdsNoLs(int Obj_Type,long StationId)
        {
            //把临时卡全部排除
            //储值卡已经没有了，不再开发，使用钱包功能
            var tbDepart = await _entityRepository.GetAll().Where(o => o.Station_ID == StationId && o.OBJ_TYPE == Obj_Type && o.OBJ_ID != 1401 && o.OBJ_ID != 1402 && o.OBJ_ID != 1403 && o.OBJ_ID != 1404 && o.OBJ_ID != 1405 && o.OBJ_ID != 1406 && o.OBJ_ID != 1407 && o.OBJ_ID != 1408).ToListAsync();

            var allTbDepart = tbDepart.MapTo<List<StationObjectsDTO>>();    

            return allTbDepart;
        }

        public async Task<List<StationObjectsDTO>> GetAllTbObjectIds(int Obj_Type,long StationId)
        {
            //把临时卡全部排除
            var tbDepart = await _entityRepository.GetAll().Where(o => o.Station_ID == StationId && o.OBJ_TYPE == Obj_Type && o.OBJ_ID != 1406 && o.OBJ_ID != 1407 && o.OBJ_ID != 1408).ToListAsync();

            var allTbDepart = tbDepart.MapTo<List<StationObjectsDTO>>();   

            return allTbDepart;
        }


        public List<TbObjectsListDto> GetAllTbObjectByOjIds(string Obj_Type1,long StationId)
        {
            List<int> strObject = new List<int>();
            if (string.IsNullOrEmpty(Obj_Type1))
            {
                strObject.Add(0);
            }
            else
            {
                for (int i = 0; i < Obj_Type1.Split(',').Length; i++)
                {
                    try{strObject.Add(Convert.ToInt32(Obj_Type1.Split(',')[i])); }  catch { }             
                }
            }
            var tbDepart = _entityRepository.GetAll().Where(o => o.Station_ID == StationId && strObject.Contains(o.OBJ_ID)).ToList();

            var allTbDepart = tbDepart.MapTo<List<TbObjectsListDto>>();    

            return allTbDepart;
        }

        /// <summary>
        /// 通过指定id获取TbObjectsListDto信息
        /// </summary>
        [AbpAuthorize(TbObjectsPermissions.Query)] 
		public async Task<TbObjectsListDto> GetById(EntityDto<long> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<TbObjectsListDto>();
		}

		/// <summary>
		/// 获取编辑 TbObjects
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbObjectsPermissions.Create,TbObjectsPermissions.Edit)]
		public async Task<GetTbObjectsForEditOutput> GetForEdit(NullableIdDto<long> input)
		{
			var output = new GetTbObjectsForEditOutput();
            TbObjectsEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<TbObjectsEditDto>(); 
			}
			else
			{
				editDto = new TbObjectsEditDto();
			}

			output.TbObjects = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改TbObjects的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbObjectsPermissions.Create,TbObjectsPermissions.Edit)]
		public async Task CreateOrUpdate(CreateOrUpdateTbObjectsInput input)
		{

			if (input.TbObjects.Id.HasValue)
			{
				await Update(input.TbObjects);
			}
			else
			{
				await Create(input.TbObjects);
			}
		}


		/// <summary>
		/// 新增TbObjects
		/// </summary>
		[AbpAuthorize(TbObjectsPermissions.Create)]
		protected virtual async Task<TbObjectsEditDto> Create(TbObjectsEditDto input)
		{
            //TODO:新增前的逻辑判断，是否允许新增
            input.Station_ID = GetCurrenUserOrganizationUnit(); 
            var entity=input.MapTo<TbObjects>();
			

			entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<TbObjectsEditDto>();
		}

		/// <summary>
		/// 编辑TbObjects
		/// </summary>
		[AbpAuthorize(TbObjectsPermissions.Edit)]
		protected virtual async Task Update(TbObjectsEditDto input)
		{
			//TODO:更新前的逻辑判断，是否允许更新

			var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);
             
		    await _entityRepository.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除TbObjects信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbObjectsPermissions.Delete)]
		public async Task Delete(EntityDto<long> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除TbObjects的方法
		/// </summary>
		[AbpAuthorize(TbObjectsPermissions.BatchDelete)]
		public async Task BatchDelete(List<long> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}


		///// <summary>
		///// 导出TbObjects为excel表,等待开发。
		///// </summary>
		///// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}

    }
}


